using Microsoft.AspNetCore.Mvc;
using JGSY.CMS.LowCode.Platform.Infrastructure.Configuration;

namespace JGSY.CMS.LowCode.Platform.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class ConfigurationMigrationController : ControllerBase
    {
        private readonly ConfigurationMigrationService _migrationService;
        private readonly CentralizedStorageConfigurationManager _configManager;

        public ConfigurationMigrationController(
            ConfigurationMigrationService migrationService,
            CentralizedStorageConfigurationManager configManager)
        {
            _migrationService = migrationService;
            _configManager = configManager;
        }

        [HttpGet("status")]
        public IActionResult GetMigrationStatus()
        {
            try
            {
                var config = _configManager.GetStorageConfiguration();
                return Ok(new
                {
                    IsUsingCentralizedConfig = config != null,
                    ConfigProvider = config?.CloudProvider ?? "Local",
                    HasLocalConfig = config?.Local != null,
                    HasCloudConfig = !string.IsNullOrEmpty(config?.CloudProvider) && config.CloudProvider != "Local"
                });
            }
            catch (Exception ex)
            {
                return BadRequest(new { error = ex.Message });
            }
        }

        [HttpPost("migrate")]
        public async Task<IActionResult> MigrateConfiguration()
        {
            try
            {
                var result = await _migrationService.MigrateToStorageConfiguration("appsettings.json");
                return Ok(result);
            }
            catch (Exception ex)
            {
                return BadRequest(new { error = ex.Message });
            }
        }

        [HttpGet("validate")]
        public IActionResult ValidateConfiguration()
        {
            try
            {
                var result = _configManager.ValidateConfiguration();
                return Ok(result);
            }
            catch (Exception ex)
            {
                return BadRequest(new { error = ex.Message });
            }
        }
    }
}
